package org.example.service.impl;

import org.example.dao.GoodsDao;
import org.example.dao.SaleDao;
import org.example.domain.Goods;
import org.example.domain.Sale;
import org.example.service.BuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("buyService")
public class BuyServiceImpl implements BuyService {

    private SaleDao saleDao;
    private GoodsDao goodsDao;

    @Autowired
    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }
    @Autowired
    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

//    /**
//     * @Transactional 放在public方法的上面，表示方法有事物功能
//     * @param goods
//     */
//    @Transactional(
//            value = "transactionManager",
//            propagation = Propagation.REQUIRED,
//            isolation = Isolation.DEFAULT,
//            readOnly = false,
//            timeout = 200,
//            rollbackFor ={NullPointerException.class}
//    )
    @Override
    @Transactional
    public void BuyGoods(List<Goods> goods) {
        for (Goods good : goods) {
            //新增銷售記錄
            Sale sale= new Sale();
            sale.setGid(good.getId());
            sale.setNums(good.getAmount());
            saleDao.insertSale(sale);

            //更新庫存
            Goods entity= goodsDao.selectGoods(good.getId());
            if(entity==null){
                throw  new NullPointerException("商品不存在");
            }
            if(entity.getAmount()<good.getAmount()){
                throw  new NullPointerException("商品庫存不足");
            }
            entity.setAmount(entity.getAmount()-good.getAmount());
            goodsDao.updateGoods(entity);
        }
    }
}
